<?php
/**
 * 团检人员
 *
 * User: kaikaic
 * Date: 2018/11/1
 * Time: 23:16
 */

namespace app\exam\controller;

use app\exam\model\GroupMemberModel;
use app\exam\service\AccountService;
use app\exam\service\EnterpriseService;
use app\exam\service\GroupMemberService;
use app\exam\service\GroupService;
use app\exam\service\GroupSetService;
use app\exam\service\MecService;
use app\exam\service\MecSetService;
use app\exam\service\ReportService;
use controller\BasicAdmin;
use service\ConfigService;
use service\ExcelService;
use PHPExcel;
use think\Db;

class GroupMember extends BasicAdmin {

    protected $table = "ExamGroupMember";

    public function index() {
        $group = $this->checkGroup();

        $this->title = "团检人员" . " / " . $group['title'];
        $query = array();
        $query['title'] = $this->request->get("title");

        $db = Db::name($this->table);
        $db->where('group_id', $group['id']);

        if ($query['title']) {
            $db->whereLike('title', "%{$query['title']}%");
        }

        $this->assign("group", $group);
        return parent::listRecord($db);
    }

    /**
     * 团检人员-新增
     */
    public function add() {
        if ($this->request->isGet()) {
            $group = $this->checkGroup();

            $vo = array();
            return view('form', [
                'title'=>'新增团检人员',
                'vo'=>$vo,
                'group'=>$group
            ]);
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->doInsertAction($data)) {
                $this->success('新增成功！', "");
            }else {
                $this->error('新增失败，请稍候再试！');
            }
        }
    }
    public function edit() {
        if ($this->request->isGet()) {
            $group = $this->checkGroup();
            $id = $this->request->get('gid', '');
            if (empty($id)) {
                $this->error('参数错误，请稍候再试！');
            }

            $vo = GroupMemberService::getInstance()->find($id);

            if (empty($vo)) {
                $this->error('记录不存在，请重新操作!');
            }
            return view('form', [
                'title'=>'编辑团检人员',
                'vo'=>$vo,
                'group'=>$group
            ]);
        }
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if ($this->doInsertAction($data)) {
                $this->success('新增成功！', "");
            }else {
                $this->error('新增失败，请稍候再试！');
            }
        }
    }
    /**
     * 数据写入
     */
    protected function doInsertAction($data) {
        $groupID = intval($this->request->post('gid', ''));
        if (!$groupID) {
            return false;
        }
        $mobile = $data['mobile'];
        if (!$this->checkMobile($mobile)) {
            return false;
        }

        // 检查用户是否已注册
        $accountID = $this->checkAccount($mobile, $data['user_name']);

        $params = array();
        $params['group_id'] = $groupID;
        $params['account_id'] = $accountID;

        if(isset($data['id']) && $data['id'] !=0){
            $groupID = intval($this->request->post('gid', ''));
            $id = intval($data['id']);
            unset($data['gid']);
            $res = GroupMemberService::getInstance()->update($data,$id);
            $record = GroupMemberService::getInstance()->find($id);
            $params['user_name'] = $data['user_name'];
            $params['mobile'] = $data['mobile'];
            $params['exam_indentity'] =   $data['exam_indentity'];
            $params['birthday'] = $data['birthday'];
            $params['married'] = $data['married'];
            $params['order_sn'] = $record['order_sn'];
            $groupinfo = Db::name('exam_group')->find($groupID);
            $groupMemberModel = new GroupMemberModel();
            return  $groupMemberModel->doUpdate($params,$groupinfo);
        }else{

        $record = GroupMemberService::getInstance()->single($params);
        if ($record) {
            return false;
        }

        $params['user_name'] = $data['user_name'];
        $params['mobile'] = $mobile;
        $params['status'] = 1;
        $params['exam_indentity'] =   $data['exam_indentity'];
        $params['birthday'] = $data['birthday'];
        $params['married'] = $data['married'];
        $params['create_time'] = time();
        $groupinfo = Db::name('exam_group')->find($groupID);
        $groupMemberModel = new GroupMemberModel();
        return  $groupMemberModel->doAdd($params,$groupinfo);
        }

    }

    /**
     * 团检人员-删除
     */
    public function remove() {
        $id = intval($this->request->post('id', ''));
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $record = GroupMemberService::getInstance()->find($id);
        if (empty($record)) {
            $this->error('记录不存在，请重新操作!');
        }

        $result = GroupMemberService::getInstance()->remove(array('id'=>$id));
        if ($result) {
            $this->success('删除成功!', '');
        }else {
            $this->error('删除失败，请重新再试!');
        }
    }

    /**
     * 人员导入(EXCEL)
     */
    public function import() {
        if ($this->request->isGet()) {
            $group = $this->checkGroup();

            return view('import', [
                'title'=>'导入团检人员',
                'group'=>$group
            ]);
        }

        if ($this->request->isPost()) {
            if ($this->doImportAction()) {
                $this->success('导入完成！', "");
            }else {
                $this->error('导入失败，请稍候再试！');
            }
        }
    }
    public function export(){
        if ($this->request->isGet()) {
            $group = $this->checkGroup();
            $db = Db::name($this->table);
            $groupmember = $db->where('group_id', $group['id'])->select();
            $objExcel = new PHPExcel();
            $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

            // 设置水平垂直居中
            $objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            // 字体和样式
            $objExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);


            //设置某一列的宽度
            $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
            $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(50);
            $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
            // 合并
            $objActSheet = $objExcel->getActiveSheet(0);
            //设置excel的标题
            $objActSheet->setCellValue('A1','姓名');
            $objActSheet->setCellValue('B1','手机号');
            $objActSheet->setCellValue('C1','订单号');
            $objActSheet->setCellValue('D1','报告地址');

            $baseRow = 2; //数据从N-1行开始往下输出 这里是避免头信息被覆盖
            foreach ( $groupmember as $r => $d ) {
                $i = $baseRow + $r;
                $objExcel->getActiveSheet()->setCellValue('A'.$i,$d['user_name']);
                $objExcel->getActiveSheet()->setCellValue('B'.$i,$d['mobile']);
                $objExcel->getActiveSheet()->setCellValue('C'.$i,$d['order_sn']);
                $objExcel->getActiveSheet()->setCellValue('D'.$i,"");
            }

            $objExcel->setActiveSheetIndex(0);
            $fileName =  date('Y-m-d') . ".xlsx";
            // type1: 保存文件

            //type2: 输出
            header('Content-Type: application/vnd.ms-excel;charset=UTF-8');
            header('Cache-Control: max-age=0');
            header("Content-Type: application/download");
            header("Content-Disposition: attachment;filename=".$group['title']."{$fileName}");

            $objWriter->save('php://output');
        }else{
            $this->error('导出失败，请稍候再试！');
        }


    }
    public function exportgroup(){
        if ($this->request->isGet()) {
            $group = $this->checkGroup();
            $db = Db::name($this->table);
            $groupmember = $db->where('group_id', $group['id'])->select();
            $objExcel = new PHPExcel();
            $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

            // 设置水平垂直居中
            $objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            // 字体和样式
            $objExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);


            //设置某一列的宽度
            $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
            $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(50);
            $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
            // 合并
            $objActSheet = $objExcel->getActiveSheet(0);
            //设置excel的标题
            $objActSheet->setCellValue('A1','姓名');
            $objActSheet->setCellValue('B1','手机号');
            $objActSheet->setCellValue('C1','订单号');
            $objActSheet->setCellValue('D1','医院');
            $objActSheet->setCellValue('E1','套餐名');
            $objActSheet->setCellValue('F1','企业名');
            $objActSheet->setCellValue('G1','下单时间');
            $objActSheet->setCellValue('H1','订单状态');
            $objActSheet->setCellValue('I1','体检状态');
            $objActSheet->setCellValue('J1','体检报告');

            $baseRow = 2; //数据从N-1行开始往下输出 这里是避免头信息被覆盖
            $orderStatus = ConfigService::examOrderStatus();
            $orderPayStatus = ConfigService::examOrderPayStatus();
            $mecList = MecService::getInstance()->listMec(1);

            foreach ( $groupmember as $r => $d ) {
                $temp = Db::name('exam_order')->where('order_sn',$d['order_sn'])->find();
                $examinfo = Db::name('exam_enterprise')->find($temp['enterprise_id']);
                $mec = MecService::getInstance()->single(array('id'=>$temp['mec_id']));
                if (!isset($mecList[$temp['mec_id']])) {
                    continue;
                }
                $temp['mec_txt'] = $mecList[$temp['mec_id']];
                $setidarr = explode(",",$temp['set_id']);
                $temp['set_txt'] = '';
                foreach ($setidarr as $key){
                    $set = MecSetService::getInstance()->single(array('id'=>$key));
                    if (!$set) {
                        continue;
                    }
                    $temp['set_txt'] .= $set['name'];
                }
                // 是否有体检报告
                $temp['report'] = '未体检';
                $temp['reportvalue'] = '';
                $report = ReportService::getInstance()->single(array('order_sn'=>$temp['order_sn']));
                if ($report) {
                    $temp['report'] = '已体检';
                    $temp['reportvalue'] = $report['name'];
                }
                $temp['order_status_txt'] = $orderStatus[$temp['order_status']];
                $i = $baseRow + $r;
                $objExcel->getActiveSheet()->setCellValue('A'.$i,$d['user_name']);
                $objExcel->getActiveSheet()->setCellValue('B'.$i,$d['mobile']);
                $objExcel->getActiveSheet()->setCellValue('C'.$i,$d['order_sn']);
                $objExcel->getActiveSheet()->setCellValue('D'.$i, $temp['mec_txt']);
                $objExcel->getActiveSheet()->setCellValue('E'.$i, $temp['set_txt']);
                $objExcel->getActiveSheet()->setCellValue('F'.$i, $examinfo['name']);
                $objExcel->getActiveSheet()->setCellValue('G'.$i, date('Y-m-d H:i',$temp['create_time']));
                $objExcel->getActiveSheet()->setCellValue('H'.$i, $temp['order_status_txt']);
                $objExcel->getActiveSheet()->setCellValue('I'.$i, $temp['report']);
                $objExcel->getActiveSheet()->setCellValue('J'.$i, $temp['reportvalue']);
            }

            $objExcel->setActiveSheetIndex(0);
            $fileName =  date('Y-m-d') . ".xlsx";
            // type1: 保存文件

            //type2: 输出
            header('Content-Type: application/vnd.ms-excel;charset=UTF-8');
            header('Cache-Control: max-age=0');
            header("Content-Type: application/download");
            header("Content-Disposition: attachment;filename=".$group['title']."{$fileName}");

            $objWriter->save('php://output');
        }else{
            $this->error('导出失败，请稍候再试！');
        }
    }
    private function doImportAction() {
        $data = $this->request->post();
        $groupID = intval($data['gid']);
        if (!$groupID) {
            return false;
        }

        $excelFile = $data['member_excel'];
        if (!$excelFile) {
            return false;
        }

        $groupMemberModel = new GroupMemberModel();
        $result = $groupMemberModel->readExcelFile($excelFile, $groupID);

        return true;
    }

    /**
     * 账号是否存在
     */
    private function checkAccount($mobile, $userName) {
        return AccountService::getInstance()->createUser($userName, $mobile, $userName);
    }

    /**
     * 列表数据处理
     */
    protected function _index_data_filter(&$data) {
        $size = count($data);
        $cfgSex = ConfigService::cfgSex();
        $cfgStatus = ConfigService::groupMemberStatus();
        $marrayStatus = ConfigService::marrayStatus();

        for ($i=0; $i<$size; $i++) {
            $temp = $data[$i];
            $temp['nick_name'] = "";
            $temp['real_name'] = "";
            $temp['sex'] = "";
            $account = AccountService::getInstance()->single(array('id'=>$temp['account_id']));
            if ($account) {
                $temp['nick_name'] = $account['nick_name'];
                $temp['real_name'] = $account['real_name'];
                $temp['sex'] = $cfgSex[$account['gender']];
            }
            $temp['status_txt'] = $cfgStatus[$temp['status']];
            $temp['marry_status'] = $marrayStatus[$temp['married']];
            $data[$i] = $temp;
        }

        $this->assign('cfg_status', $cfgStatus);
    }

    private function checkGroup() {
        $groupID = intval($this->request->get('id', ''));
        if (empty($groupID)) {
            $this->error('参数错误，请稍候再试！');
        }

        $group = GroupService::getInstance()->find($groupID);
        if (empty($group)) {
            $this->error('记录不存在，请重新操作!');
        }

        return $group;
    }

    /**
     * 手机号码是否正确
     */
    private function checkMobile($mobile) {
        return preg_match('/^0?(13|15|17|18|14)[0-9]{9}$/i', $mobile);
    }
}

